import subprocess
import os

def merge_m4s_files(subfolder_path):
    # 构建视频和音频文件的完整路径
    video_path = os.path.join(subfolder_path, 'video.m4s')
    audio_path = os.path.join(subfolder_path, 'audio.m4s')
    # 构建输出文件的完整路径，使其位于子文件夹内
    output_path = os.path.join(subfolder_path, 'output.mp4')

    # 检查视频和音频文件是否存在
    if not os.path.exists(video_path):
        print(f"视频文件 {video_path} 不存在。")
        return
    if not os.path.exists(audio_path):
        print(f"音频文件 {audio_path} 不存在。")
        return

    # 构建 ffmpeg 命令
    command = [
        'ffmpeg',
        '-i', video_path,
        '-i', audio_path,
        '-codec', 'copy',
        output_path
    ]

    try:
        # 执行 ffmpeg 命令
        subprocess.run(command, check=True)
        print(f"合并成功，输出文件为 {output_path}")
    except subprocess.CalledProcessError as e:
        print(f"合并失败: {e}")
    except FileNotFoundError:
        print("未找到 ffmpeg 可执行文件，请确保已经安装并配置了 ffmpeg。")


def traverse_folders(root_folder):
    # 遍历根文件夹下的所有子文件夹
    for root, dirs, files in os.walk(root_folder):
        for dir in dirs:
            subfolder_path = os.path.join(root, dir)
            # 调用合并函数
            merge_m4s_files(subfolder_path)


if __name__ == "__main__":
    # 获取用户输入的根文件夹路径
    root_folder = input("请输入包含子文件夹的根文件夹路径: ")
    traverse_folders(root_folder)
